package com.csust.automaticteach.app.agent;

import cn.hutool.core.util.StrUtil;
import com.csust.automaticteach.app.agent.model.AgentState;
import com.csust.automaticteach.exception.BusinessException;
import com.csust.automaticteach.exception.ErrorCode;
import lombok.Data;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;

import java.util.ArrayList;
import java.util.List;

import static com.csust.automaticteach.constant.ExceptionConstant.PROMPT_CANNOT_BE_NULL;
import static com.csust.automaticteach.constant.ExceptionConstant.RUNNING_ERROR;

/**
 * @ClassNameBaseAgent
 * @Description 基本Agent类  定义代理类
 * @Author钰玟
 * @Date2025/6/17 下午10:03
 * @Version 1.0
 **/
@Data
@Slf4j
@Setter
public abstract class BaseAgent {
    /**
     * 名称
     */
    private String name;
    /**
     * 提示
     */
    private String systemPrompt;
    /**
     * 下一步的提示
     */
    private String nextStepPrompt;
    /**
     * 当前步骤数目
     */
    private int currentStep = 0;
    /**
     * 最大步骤数目
     */
    private int maxStep = 20;
    /**
     * 当前状态
     */
    private AgentState state = AgentState.IDLE;
    /**
     * AI 大模型
     */
    private ChatClient chatClient;
    /**
     * 对话记忆
     */
    private final List<Message> messageList = new ArrayList<>();

    public void setMessageList(List<Message> messageList) {
        this.messageList.clear();
        this.messageList.addAll(messageList);
    }

    /**
     * 运行代理
     *
     * @return 返回结果
     */
    public String run(String userPrompt) {
        //1. 判断当前状态是否为空闲
        if (state != AgentState.IDLE) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, RUNNING_ERROR);
        }
        //2.判断用户提示词是否为空
        if (StrUtil.isBlank(userPrompt)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, PROMPT_CANNOT_BE_NULL);
        }
        //运行代理 =>设位置状态为运行中
        state = AgentState.RUNNING;
        //添加当前用户消息为上下文记忆
        messageList.add(new UserMessage(userPrompt));
        //结果数组  由于ai可能会多次调用大模型，维护一个结果数组
        List<String> results = new ArrayList<>();
        try {
            for (int i = 0; i < maxStep && state != AgentState.FINISHED; i++) {
                int stepNumber = i + 1;
                currentStep = stepNumber;
                //打印日志
                log.info("Executing step" + currentStep + "/" + maxStep);
                //执行
                String stepResult = step();
                //拼接结果消息
                String result = "Step" + currentStep + "result:" + stepResult;
                //插入消息
                results.add(result);
            }
            if (currentStep >= maxStep) {
                currentStep = 0;
                state = AgentState.FINISHED;
                log.info("Finished running agent");
                results.add("Terminated: Reached max steps" + maxStep);
            }
            return String.join("\n", results);
        } catch (Exception e) {
            state = AgentState.ERROR;
            log.error("Error running agent" + e.getMessage());
            return "Executing Error:" + e.getMessage();
        } finally {
            //清理资源
            cleanup();
        }


    }

    public abstract String step();

    protected void cleanup() {
        //定义清理资源的方法
    }
}
